package com.can.controller;

import com.can.common.exception.UserException;
import com.can.common.validate.InsertValidate;
import com.can.entityDTO.JsonResult;
import com.can.entityDTO.UserDTO;
import com.can.service.user.IUserService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * @Description 用户控制类
 * @Author can
 * @Date 2018/8/28
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    protected static String REDIRECT = "redirect:";
    @Autowired
    private IUserService userService;
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/hello")
    public String helloHtml() {
        return "hello";
    }

    @GetMapping("/aa")
    public String aPage() {
        return "a";
    }

    @PostMapping("/test")
    @ResponseBody
    public JsonResult test() {
        return JsonResult.createSuccess("访问到了");
    }

    @PostMapping("/login")
    @ResponseBody
    public JsonResult login(@Valid @RequestBody UserDTO user) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), user.getPassword(), user.getRememberMe());
        //4、登录，即身份验证
        subject.login(token);
        return JsonResult.createSuccess(null);
    }

    @PostMapping("/register")
    @ResponseBody
    public JsonResult register(@Validated(value = InsertValidate.class) @RequestBody UserDTO user)throws UserException{
        try {
            int result = userService.register(user);
            return JsonResult.createSuccess(result);
        }catch (DuplicateKeyException e){
            throw new UserException("账户名已经存在!",e);
        }
    }

    /**
     * 获取图形验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @GetMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}